package com.test.service;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.test.entity.User;
import com.test.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 查询所有的excel数据
     *
     * @return
     */
    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    /**
     * 导入excel数据到数据库
     *
     * @param excelFile 表单传递的文件
     */
    @Override
    public void saveAll(MultipartFile excelFile) throws Exception {
        //参数1:文件输入流 参数2:实体类类型 参数3:导入的配置信息
        ImportParams params = new ImportParams();
        params.setTitleRows(1);  //文件标题所占行数
        params.setHeadRows(1);  //文件的列名所占的行数
        List<User> users = ExcelImportUtil.importExcel(excelFile.getInputStream(), User.class, params);
        for (User user : users) {
            user.setId(null);  //使用数据库自增id
            //System.out.println(user);
            String fileName = user.getPhoto().substring(user.getPhoto().lastIndexOf("\\") + 1);
            System.out.println("图片名称 : " +  fileName);
            user.setPhoto(fileName);
            userMapper.saveAll(user);
        }
    }

}
